/**
 * ============================================
 * 管理后台逻辑文件
 * Three.js Project Admin Panel Manager
 * 版本: 4.2.1 (修复showToast未定义的问题)
 * ============================================
 */

import projectAPI from '../project/projectAPI.js';

// 版本信息

// ============================================
// 全局变量
// ============================================

// 账号管理API基础URL
const API_BASE_URL = '/api';

let currentConfig = {};
let allProjects = [];
let selectedProjectForScenes = null;
let selectedProjectId = null; // 当前选中的项目ID

// ============================================
// 初始化
// ============================================

document.addEventListener('DOMContentLoaded', function() {
    checkAdminAuth();
    initEventListeners();
    window.projectAPI = projectAPI; // 暴露到全局以便调试
});

// ============================================
// 认证相关函数
// ============================================

// 检查管理员认证
function checkAdminAuth() {
    const isAdminLoggedIn = localStorage.getItem('adminLoggedIn');
    const adminUser = localStorage.getItem('adminUser');
    
    if (isAdminLoggedIn === 'true' && adminUser) {
        showAdminPanel(adminUser);
    } else {
        showLoginPanel();
    }
}

// 显示登录面板
function showLoginPanel() {
    const loginContainer = document.getElementById('loginContainer');
    const adminContainer = document.getElementById('adminContainer');
    
    loginContainer.classList.add('active');
    adminContainer.classList.remove('active');
    
    // 重置登录按钮状态（修复注销后按钮卡住的问题）
    const loginForm = document.getElementById('adminLoginForm');
    if (loginForm) {
        const submitBtn = loginForm.querySelector('button[type="submit"]');
        const loading = submitBtn?.querySelector('.loading');
        
        if (submitBtn) {
            submitBtn.disabled = false;
        }
        if (loading) {
            loading.classList.add('hidden');
        }
    }
    
    // 清空错误提示
    const errorDiv = document.getElementById('loginError');
    if (errorDiv) {
        errorDiv.style.display = 'none';
    }
}

// 显示管理面板
function showAdminPanel(username) {
    const loginContainer = document.getElementById('loginContainer');
    const adminContainer = document.getElementById('adminContainer');
    
    loginContainer.classList.remove('active');
    adminContainer.classList.add('active');
    
    document.getElementById('currentAdmin').textContent = username;
    loadConfig();
    loadProjects(); // 加载项目列表
}

// 处理管理员登录
async function handleAdminLogin(e) {
    e.preventDefault();
    
    const username = document.getElementById('adminUsername').value.trim();
    const password = document.getElementById('adminPassword').value.trim();
    const errorDiv = document.getElementById('loginError');
    const submitBtn = e.target.querySelector('button[type="submit"]');
    const loading = submitBtn.querySelector('.loading');
    
    // 显示加载状态
    loading.classList.remove('hidden');
    submitBtn.disabled = true;
    errorDiv.style.display = 'none';
    
    try {
        // 调用后端API验证管理员登录
        const response = await fetch(`${API_BASE_URL}/auth/admin-login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });
        
        const result = await response.json();
        
        if (result.success) {
            // 登录成功 - 重置UI状态
            loading.classList.add('hidden');
            submitBtn.disabled = false;
            
            localStorage.setItem('adminLoggedIn', 'true');
            localStorage.setItem('adminUser', username);
            localStorage.setItem('adminUserData', JSON.stringify(result.data));
            showAdminPanel(username);
        } else {
            // 登录失败 - 重置UI状态
            loading.classList.add('hidden');
            submitBtn.disabled = false;
            errorDiv.textContent = result.error || '登录失败';
            errorDiv.style.display = 'block';
            
            // 清空密码
            document.getElementById('adminPassword').value = '';
        }
    } catch (error) {
        console.error('❌ 管理员登录失败:', error);
        
        // 网络错误 - 重置UI状态
        loading.classList.add('hidden');
        submitBtn.disabled = false;
        errorDiv.textContent = '网络错误，请稍后重试';
        errorDiv.style.display = 'block';
        
        // 清空密码
        document.getElementById('adminPassword').value = '';
    }
}

// 管理员退出登录
async function adminLogout() {
    const confirmed = await showConfirm('确定要退出管理后台吗？', {
        title: '退出登录',
        type: 'info',
        okText: '退出',
        cancelText: '取消'
    });
    
    if (confirmed) {
        localStorage.removeItem('adminLoggedIn');
        localStorage.removeItem('adminUser');
        showLoginPanel();
        
        // 清空表单
        document.getElementById('adminLoginForm').reset();
    }
}

// 将退出登录函数暴露到全局
window.adminLogout = adminLogout;

// ============================================
// 事件监听器
// ============================================

function initEventListeners() {
    // 登录表单
    document.getElementById('adminLoginForm').addEventListener('submit', handleAdminLogin);

    // 导航菜单
    document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', function(e) {
            e.preventDefault();
            switchSection(this.dataset.section);
            
            // 更新活跃状态
            document.querySelectorAll('.nav-item').forEach(nav => nav.classList.remove('active'));
            this.classList.add('active');
        });
    });

    // 滑块值更新
    document.querySelectorAll('input[type="range"]').forEach(range => {
        range.addEventListener('input', function() {
            const valueSpan = document.getElementById(this.id + '-value');
            if (valueSpan) {
                valueSpan.textContent = this.value;
            }
        });
    });
    
    // 项目登录授权开关 - 立即同步
    const authEnabledCheckbox = document.getElementById('auth-enabled');
    if (authEnabledCheckbox) {
        authEnabledCheckbox.addEventListener('change', async function() {
            const isEnabled = this.checked;
            // 收集当前配置
            const config = collectConfigFromForm();
            
            // 立即保存到服务器
            const success = await saveConfigToServer(config, true);
            
            if (success) {
                showToast(
                    `项目登录授权已${isEnabled ? '开启' : '关闭'}，配置已同步`,
                    'success',
                    3000
                );
            }
        });
    }
    
    // 添加配置自动保存监听器
    addAutoSaveListeners();
}

// 切换配置区域
function switchSection(sectionName) {
    // 隐藏所有区域
    document.querySelectorAll('.section').forEach(section => {
        section.classList.remove('active');
    });
    
    // 显示目标区域
    const targetSection = document.getElementById(sectionName + '-section');
    if (targetSection) {
        targetSection.classList.add('active');
    }
    
    // 特殊处理：切换到回收站时自动加载列表
    if (sectionName === 'recycle-bin') {
        loadRecycleBin();
    }
}

// ============================================
// 配置管理功能
// ============================================

// 加载配置
async function loadConfig() {
    try {
        const response = await fetch('/api/config');
        if (!response.ok) {
            throw new Error(`后端API配置加载失败: HTTP ${response.status}`);
        }
        
        const result = await response.json();
        if (!result.success) {
            throw new Error(result.error || '配置加载失败');
        }
        
        currentConfig = result.data;
        populateConfigForm(currentConfig);
        updatePreview();
        
        // 加载资源管理的项目列表
        await loadResourceProjectSelector();
    } catch (error) {
        console.error('❌ 配置加载失败:', error);
        showAlert('无法从后端加载配置，请确保后端API服务器正在运行', 'error');
        
        // 显示错误提示
        const configContent = document.getElementById('configContent');
        if (configContent) {
            configContent.innerHTML = `
                <div style="padding: 40px; text-align: center; color: #ff6b6b;">
                    <h3>❌ 配置加载失败</h3>
                    <p>${error.message}</p>
                    <p>请确保后端API服务器正在运行 (http://localhost:7283)</p>
                    <button onclick="location.reload()" style="margin-top: 20px; padding: 10px 20px; background: #667eea; color: white; border: none; border-radius: 6px; cursor: pointer;">
                        重新加载
                    </button>
                </div>
            `;
        }
    }
}

// 注意：所有配置都必须从后端API读取，不再提供默认值

// 填充配置表单
function populateConfigForm(config) {
    // 认证设置 - 从后端API获取的配置
    const authEnabled = document.getElementById('auth-enabled');
    if (authEnabled) authEnabled.checked = config.auth?.enabled ?? false;

    const authSessionTimeout = document.getElementById('auth-sessionTimeout');
    if (authSessionTimeout) authSessionTimeout.value = config.auth?.sessionTimeout ?? '';
    
    // 注意：项目用户名和管理员用户名是只读的，密码字段用于输入新密码，不需要填充

    // UI设置 - 从后端API获取的配置
    document.getElementById('ui-theme').value = config.ui?.theme;
    document.getElementById('ui-showUserInfo').checked = config.ui?.showUserInfo;
    document.getElementById('ui-showCameraTips').checked = config.ui?.showCameraTips;
    document.getElementById('ui-showSceneInfo').checked = config.ui?.showSceneInfo;
    document.getElementById('ui-panelPosition').value = config.ui?.panelPosition;
    document.getElementById('ui-panelOpacity').value = config.ui?.panelOpacity;
    document.getElementById('ui-panelOpacity-value').textContent = config.ui?.panelOpacity;

    // 相机设置 - 从后端API获取
    document.getElementById('camera-defaultPosition').value = config.camera?.defaultPosition?.join(', ');
    document.getElementById('camera-defaultTarget').value = config.camera?.defaultTarget?.join(', ');
    document.getElementById('camera-minPolarAngle').value = config.camera?.minPolarAngle;
    document.getElementById('camera-minPolarAngle-value').textContent = config.camera?.minPolarAngle;
    document.getElementById('camera-maxPolarAngle').value = config.camera?.maxPolarAngle;
    document.getElementById('camera-maxPolarAngle-value').textContent = config.camera?.maxPolarAngle;
    document.getElementById('camera-enableDamping').checked = config.camera?.enableDamping;
    document.getElementById('camera-dampingFactor').value = config.camera?.dampingFactor;
    document.getElementById('camera-dampingFactor-value').textContent = config.camera?.dampingFactor;
    document.getElementById('camera-enableZoom').checked = config.camera?.enableZoom;
    document.getElementById('camera-zoomSpeed').value = config.camera?.zoomSpeed;
    document.getElementById('camera-zoomSpeed-value').textContent = config.camera?.zoomSpeed;
    document.getElementById('camera-enablePan').checked = config.camera?.enablePan;
    document.getElementById('camera-panSpeed').value = config.camera?.panSpeed;
    document.getElementById('camera-panSpeed-value').textContent = config.camera?.panSpeed;
    document.getElementById('camera-enableRotate').checked = config.camera?.enableRotate;
    document.getElementById('camera-rotateSpeed').value = config.camera?.rotateSpeed;
    document.getElementById('camera-rotateSpeed-value').textContent = config.camera?.rotateSpeed;

    // 编辑器设置 - 从后端API获取
    document.getElementById('editor-enableGeometryLibrary').checked = config.editor?.enableGeometryLibrary;
    document.getElementById('editor-enableModelLibrary').checked = config.editor?.enableModelLibrary;
    document.getElementById('editor-defaultModelPath').value = config.editor?.defaultModelPath;
    document.getElementById('editor-previewOpacity').value = config.editor?.previewOpacity;
    document.getElementById('editor-previewOpacity-value').textContent = config.editor?.previewOpacity;
    document.getElementById('editor-previewAnimation').checked = config.editor?.previewAnimation;
    document.getElementById('editor-dragLabelEnabled').checked = config.editor?.dragLabelEnabled;

    // 性能设置 - 从后端API获取
    document.getElementById('performance-enableShadows').checked = config.performance?.enableShadows;
    document.getElementById('performance-shadowMapSize').value = config.performance?.shadowMapSize;
    document.getElementById('performance-antialias').checked = config.performance?.antialias;
    document.getElementById('performance-maxFPS').value = config.performance?.maxFPS;
    document.getElementById('performance-enableStats').checked = config.performance?.enableStats;

    // 调试设置 - 从后端API获取
    document.getElementById('debug-enabled').checked = config.debug?.enabled;
    document.getElementById('debug-showConsole').checked = config.debug?.showConsole;
    document.getElementById('debug-logLevel').value = config.debug?.logLevel;
    document.getElementById('debug-showFPS').checked = config.debug?.showFPS;
    document.getElementById('debug-showMemory').checked = config.debug?.showMemory;
}

// 从表单收集配置
function collectConfigFromForm() {
    const config = {
        auth: {
            enabled: document.getElementById('auth-enabled').checked,
            defaultUsername: '123', // 固定项目用户名（保留）
            defaultPassword: '123', // 项目默认密码（保留）
            sessionTimeout: parseInt(document.getElementById('auth-sessionTimeout').value)
        },
        ui: {
            theme: document.getElementById('ui-theme').value,
            showUserInfo: document.getElementById('ui-showUserInfo').checked,
            showCameraTips: document.getElementById('ui-showCameraTips').checked,
            showSceneInfo: document.getElementById('ui-showSceneInfo').checked,
            panelPosition: document.getElementById('ui-panelPosition').value,
            panelOpacity: parseFloat(document.getElementById('ui-panelOpacity').value)
        },
        camera: {
            defaultPosition: document.getElementById('camera-defaultPosition').value.split(',').map(v => parseFloat(v.trim())),
            defaultTarget: document.getElementById('camera-defaultTarget').value.split(',').map(v => parseFloat(v.trim())),
            minPolarAngle: parseFloat(document.getElementById('camera-minPolarAngle').value),
            maxPolarAngle: parseFloat(document.getElementById('camera-maxPolarAngle').value),
            enableDamping: document.getElementById('camera-enableDamping').checked,
            dampingFactor: parseFloat(document.getElementById('camera-dampingFactor').value),
            enableZoom: document.getElementById('camera-enableZoom').checked,
            zoomSpeed: parseFloat(document.getElementById('camera-zoomSpeed').value),
            enablePan: document.getElementById('camera-enablePan').checked,
            panSpeed: parseFloat(document.getElementById('camera-panSpeed').value),
            enableRotate: document.getElementById('camera-enableRotate').checked,
            rotateSpeed: parseFloat(document.getElementById('camera-rotateSpeed').value)
        },
        editor: {
            enableGeometryLibrary: document.getElementById('editor-enableGeometryLibrary').checked,
            enableModelLibrary: document.getElementById('editor-enableModelLibrary').checked,
            defaultModelPath: document.getElementById('editor-defaultModelPath').value,
            previewOpacity: parseFloat(document.getElementById('editor-previewOpacity').value),
            previewAnimation: document.getElementById('editor-previewAnimation').checked,
            dragLabelEnabled: document.getElementById('editor-dragLabelEnabled').checked
        },
        performance: {
            enableShadows: document.getElementById('performance-enableShadows').checked,
            shadowMapSize: parseInt(document.getElementById('performance-shadowMapSize').value),
            antialias: document.getElementById('performance-antialias').checked,
            maxFPS: parseInt(document.getElementById('performance-maxFPS').value),
            enableStats: document.getElementById('performance-enableStats').checked
        },
        debug: {
            enabled: document.getElementById('debug-enabled').checked,
            showConsole: document.getElementById('debug-showConsole').checked,
            logLevel: document.getElementById('debug-logLevel').value,
            showFPS: document.getElementById('debug-showFPS').checked,
            showMemory: document.getElementById('debug-showMemory').checked
        }
    };
    
    return config;
}

// 保存配置到服务器
async function saveConfigToServer(config, showNotification = false) {
    try {
        const response = await fetch(`${API_BASE_URL}/config/save`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(config)
        });
        
        const result = await response.json();
        
        if (result.success) {
            currentConfig = config;
            updatePreview();
            
            if (showNotification) {
                showToast('配置保存成功', 'success');
            }
            
            return true;
        } else {
            throw new Error(result.error || '保存失败');
        }
    } catch (error) {
        console.error('❌ 配置保存失败:', error);
        if (showNotification) {
            showToast('配置保存失败: ' + error.message, 'error');
        }
        return false;
    }
}

// 自动保存配置（防抖）
let saveTimeout = null;
async function autoSaveConfig() {
    // 清除之前的定时器
    if (saveTimeout) {
        clearTimeout(saveTimeout);
    }
    
    // 延迟500ms保存，避免频繁保存
    saveTimeout = setTimeout(async () => {
        try {
            const config = collectConfigFromForm();
            
            // 验证配置
            if (!validateConfig(config)) {
                return;
            }
            
            // 保存到服务器
            await saveConfigToServer(config, false);
        } catch (error) {
            console.error('❌ 配置保存失败:', error);
        }
    }, 500);
}

// 添加自动保存监听器
function addAutoSaveListeners() {
    // 监听所有输入框、选择框、复选框的变化
    const inputs = document.querySelectorAll('#auth-section input, #auth-section select, #auth-section textarea, ' +
        '#ui-section input, #ui-section select, #ui-section textarea, ' +
        '#camera-section input, #camera-section select, #camera-section textarea, ' +
        '#editor-section input, #editor-section select, #editor-section textarea, ' +
        '#performance-section input, #performance-section select, #performance-section textarea, ' +
        '#debug-section input, #debug-section select, #debug-section textarea');
    
    inputs.forEach(input => {
        if (input.type === 'checkbox') {
            input.addEventListener('change', autoSaveConfig);
        } else if (input.type === 'range') {
            input.addEventListener('change', autoSaveConfig); // range用change而不是input
        } else {
            input.addEventListener('input', autoSaveConfig);
        }
    });
}

// 刷新预览
function refreshPreview() {
    const config = collectConfigFromForm();
    updatePreview(config);
}

// 更新预览
function updatePreview(config = currentConfig) {
    const preview = document.getElementById('configPreview');
    if (preview) {
        preview.value = JSON.stringify(config, null, 2);
    }
}

// 复制配置
async function copyConfig() {
    const preview = document.getElementById('configPreview');
    try {
        await navigator.clipboard.writeText(preview.value);
        showAlert('配置已复制到剪贴板', 'success');
    } catch (error) {
        // 降级方案
        preview.select();
        document.execCommand('copy');
        showAlert('配置已复制到剪贴板', 'success');
    }
}

// 验证配置
function validateConfig(config) {
    // 基本验证
    if (!config.auth || typeof config.auth.sessionTimeout !== 'number') {
        showAlert('认证配置无效', 'error');
        return false;
    }
    
    if (!config.camera || !Array.isArray(config.camera.defaultPosition)) {
        showAlert('相机配置无效', 'error');
        return false;
    }
    
    return true;
}

// 暴露到全局
window.refreshPreview = refreshPreview;
window.copyConfig = copyConfig;

// ============================================
// UI工具函数
// ============================================

// 显示提示消息（Toast通知）
function showAlert(message, type = 'success', duration = 3000) {
    const container = document.getElementById('toastContainer');
    if (!container) {
        console.warn('Toast container not found');
        return;
    }
    
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    
    // 添加图标
    const icon = type === 'success' ? '✓' : '✕';
    toast.innerHTML = `<span style="font-size: 18px; font-weight: bold;">${icon}</span><span>${message}</span>`;
    
    container.appendChild(toast);
    
    // 自动移除
    setTimeout(() => {
        toast.style.animation = 'slideOut 0.3s ease-out';
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, duration);
}

// showToast 别名（与 showAlert 功能相同）
const showToast = showAlert;

// 自定义确认对话框
function showConfirm(message, options = {}) {
    return new Promise((resolve) => {
        const dialog = document.getElementById('confirmDialog');
        const icon = document.getElementById('confirmIcon');
        const title = document.getElementById('confirmTitle');
        const messageEl = document.getElementById('confirmMessage');
        const okBtn = document.getElementById('confirmOkBtn');
        const cancelBtn = document.getElementById('confirmCancelBtn');
        
        // 设置类型（danger/warning/info）
        const type = options.type || 'warning';
        const iconEmoji = type === 'danger' ? '🗑️' : type === 'info' ? 'ℹ️' : '⚠️';
        
        icon.textContent = iconEmoji;
        icon.className = `confirm-icon ${type}`;
        title.textContent = options.title || '确认操作';
        messageEl.textContent = message;
        
        // 设置确认按钮样式
        okBtn.className = `confirm-btn confirm-btn-confirm ${type === 'danger' ? 'danger' : ''}`;
        okBtn.textContent = options.okText || '确定';
        cancelBtn.textContent = options.cancelText || '取消';
        
        // 显示对话框
        dialog.classList.add('active');
        
        // 处理确认
        function handleConfirm() {
            dialog.classList.remove('active');
            cleanup();
            resolve(true);
        }
        
        // 处理取消
        function handleCancel() {
            dialog.classList.remove('active');
            cleanup();
            resolve(false);
        }
        
        // 清理事件监听器
        function cleanup() {
            okBtn.removeEventListener('click', handleConfirm);
            cancelBtn.removeEventListener('click', handleCancel);
            dialog.removeEventListener('click', handleOverlayClick);
            document.removeEventListener('keydown', handleKeyDown);
        }
        
        // 点击遮罩关闭
        function handleOverlayClick(e) {
            if (e.target === dialog) {
                handleCancel();
            }
        }
        
        // ESC键关闭
        function handleKeyDown(e) {
            if (e.key === 'Escape') {
                handleCancel();
            }
        }
        
        // 绑定事件
        okBtn.addEventListener('click', handleConfirm);
        cancelBtn.addEventListener('click', handleCancel);
        dialog.addEventListener('click', handleOverlayClick);
        document.addEventListener('keydown', handleKeyDown);
        
        // 聚焦确认按钮
        setTimeout(() => okBtn.focus(), 100);
    });
}

// ============================================
// 项目管理功能
// ============================================

// 加载项目列表
async function loadProjects() {
    const container = document.getElementById('projectsContainer');
    container.innerHTML = '<div class="loading" style="text-align: center; padding: 40px;">加载中...</div>';
    
    try {
        const data = await projectAPI.getAllProjects();
        allProjects = data.projects || [];
        
        
        if (allProjects.length === 0) {
            container.innerHTML = '<div style="text-align: center; padding: 40px; color: #999;">暂无项目</div>';
            // 清空选中状态
            selectedProjectId = null;
            const createSceneBtn = document.getElementById('createSceneBtn');
            if (createSceneBtn) createSceneBtn.disabled = true;
            return;
        }
        
        const currentProjectId = localStorage.getItem('currentProjectId');
        
        // 如果当前选中的项目已被删除，清空选中状态
        if (selectedProjectId && !allProjects.find(p => p.id === selectedProjectId)) {
            selectedProjectId = null;
            const createSceneBtn = document.getElementById('createSceneBtn');
            if (createSceneBtn) createSceneBtn.disabled = true;
        }
        
        let html = `
            <table class="data-table">
                <thead>
                    <tr>
                        <th>项目名称</th>
                        <th>描述</th>
                        <th>场景数</th>
                        <th>批量下载并发数</th>
                        <th>状态</th>
                        <th>更新时间</th>
                        <th style="width: 240px;">操作</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        allProjects.forEach((project, index) => {
            // 只使用defaultProject字段判断默认项目，确保只有一个默认
            const isDefault = project.id === data.defaultProject;
            const isSelected = project.id === selectedProjectId;
            const sceneCount = project.scenes?.length || 0;
            const maxConcurrent = project.maxConcurrentDownloads || 3; // 默认值为3
            const updatedAt = new Date(project.updatedAt || project.createdAt).toLocaleString('zh-CN');
            
            html += `
                <tr class="${isSelected ? 'selected-row' : ''}">
                    <td>
                        <strong class="project-name-link" 
                                onclick="selectProject('${project.id}')" 
                                title="点击查看该项目的场景列表">
                            ${isSelected ? '▶ ' : ''}${project.name}
                        </strong>
                    </td>
                    <td>${project.description || '-'}</td>
                    <td>${sceneCount}</td>
                    <td>
                        <span class="badge badge-concurrent" style="background: #4a9eff; color: white; padding: 4px 8px; border-radius: 4px; font-size: 12px;">
                            ${maxConcurrent}
                        </span>
                    </td>
                    <td>
                        ${isDefault ? '<span class="badge badge-default">默认</span>' : ''}
                    </td>
                    <td>${updatedAt}</td>
                    <td>
                        <button type="button" class="btn-sm btn-edit" onclick="openProjectSettingsModal('${project.id}')" title="编辑项目设置">⚙️ 设置</button>
                        ${!isDefault ? `<button type="button" class="btn-sm btn-switch" onclick="setDefaultProject('${project.id}', '${project.name.replace(/'/g, "\\'")}')">设为默认</button>` : ''}
                        ${!isDefault ? `<button type="button" class="btn-sm btn-delete" onclick="deleteProject('${project.id}', '${project.name.replace(/'/g, "\\'")}')">删除</button>` : '<span style="color: #999; font-size: 12px;">默认</span>'}
                    </td>
                </tr>
            `;
        });
        
        html += '</tbody></table>';
        container.innerHTML = html;
        
        // 保持创建场景按钮的状态
        const createSceneBtn = document.getElementById('createSceneBtn');
        if (createSceneBtn && selectedProjectId) {
            createSceneBtn.disabled = false;
        }
        
    } catch (error) {
        console.error('加载项目失败:', error);
        container.innerHTML = `<div style="text-align: center; padding: 40px; color: #e53e3e;">加载失败: ${error.message}</div>`;
    }
}

// 刷新管理界面
window.refreshManagement = async function() {
    await loadProjects();
    await loadProjectScenes();
    showAlert('数据已刷新', 'success');
};

// 只更新指定项目的场景数（不重新加载整个列表）
async function updateProjectSceneCount(projectId) {
    try {
        // 获取最新的项目数据
        const projectData = await projectAPI.getProject(projectId);
        const sceneCount = projectData.scenes?.length || 0;
        
        // 更新 allProjects 数组中的数据
        const projectIndex = allProjects.findIndex(p => p.id === projectId);
        if (projectIndex !== -1) {
            allProjects[projectIndex].scenes = projectData.scenes;
        }
        
        // 只更新DOM中该项目行的场景数显示
        const projectRows = document.querySelectorAll('#projectsContainer .data-table tbody tr');
        projectRows.forEach((row, index) => {
            if (allProjects[index] && allProjects[index].id === projectId) {
                const sceneCountCell = row.querySelectorAll('td')[3]; // 场景数是第4列（索引3）
                if (sceneCountCell) {
                    sceneCountCell.textContent = sceneCount;
                }
            }
        });
    } catch (error) {
        console.error('❌ 更新场景数失败:', error);
        // 静默失败，不影响用户体验
    }
}


// 删除项目（移入回收站）
window.deleteProject = async function(projectId, projectName) {
    const confirmed = await showConfirm(
        `确定要删除项目 "${projectName}" 吗？\n\n项目将移入回收站，30天内可以恢复。`,
        {
            title: '删除项目',
            type: 'danger',
            okText: '删除',
            cancelText: '取消'
        }
    );
    
    if (!confirmed) {
        return;
    }
    
    try {
        // 检查是否删除的是当前选中的项目
        const isDeletingSelectedProject = (projectId === selectedProjectId);
        
        await projectAPI.deleteProject(projectId);
        showAlert('项目已移入回收站，30天后将自动删除', 'success');
        
        // 如果删除的是当前选中的项目，清空场景列表
        if (isDeletingSelectedProject) {
            selectedProjectId = null;
            
            // 清空场景列表显示
            const sceneContainer = document.getElementById('sceneListContainer');
            const projectNameDisplay = document.getElementById('selectedProjectName');
            const createSceneBtn = document.getElementById('createSceneBtn');
            
            if (sceneContainer) {
                sceneContainer.innerHTML = '<div style="text-align: center; padding: 40px; color: #999;">请先选择项目</div>';
            }
            if (projectNameDisplay) {
                projectNameDisplay.textContent = '';
            }
            if (createSceneBtn) {
                createSceneBtn.disabled = true;
            }
        }
        
        // 刷新项目列表
        await loadProjects();
    } catch (error) {
        showAlert('删除项目失败: ' + error.message, 'error');
    }
};

// ============================================
// 回收站管理
// ============================================

// 加载回收站列表
async function loadRecycleBin() {
    const container = document.getElementById('recycleBinContainer');
    
    try {
        const response = await fetch(`${API_BASE_URL}/projects/recycle-bin/list`);
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || '获取回收站列表失败');
        }
        
        const recycleBinProjects = result.data;
        
        if (recycleBinProjects.length === 0) {
            container.innerHTML = `
                <div class="empty-state" style="text-align: center; padding: 60px 20px; color: #999;">
                    <div style="font-size: 48px; margin-bottom: 20px;">🗑️</div>
                    <p style="font-size: 16px;">回收站为空</p>
                </div>
            `;
            return;
        }
        
        let html = `
            <table class="data-table">
                <thead>
                    <tr>
                        <th style="width: 25%;">项目名称</th>
                        <th style="width: 30%;">描述</th>
                        <th style="width: 15%;">删除时间</th>
                        <th style="width: 12%;">剩余天数</th>
                        <th style="width: 18%;">操作</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        recycleBinProjects.forEach(project => {
            const deletedDate = new Date(project.deletedAt);
            const deletedDateStr = deletedDate.toLocaleDateString('zh-CN');
            const daysLeftClass = project.daysLeft <= 7 ? 'style="color: #f56565; font-weight: 600;"' : '';
            
            html += `
                <tr>
                    <td><strong>${project.name}</strong></td>
                    <td style="color: #999;">${project.description || '无描述'}</td>
                    <td>${deletedDateStr}</td>
                    <td ${daysLeftClass}>${project.daysLeft} 天</td>
                    <td>
                        <button type="button" class="btn-sm btn-success" onclick="restoreProject('${project.id}', '${project.name.replace(/'/g, "\\'")}')">恢复</button>
                        <button type="button" class="btn-sm btn-delete" onclick="permanentlyDeleteProject('${project.id}', '${project.name.replace(/'/g, "\\'")}')">彻底删除</button>
                    </td>
                </tr>
            `;
        });
        
        html += '</tbody></table>';
        container.innerHTML = html;
        
    } catch (error) {
        console.error('❌ 加载回收站列表失败:', error);
        container.innerHTML = `
            <div class="empty-state" style="text-align: center; padding: 40px; color: #f56565;">
                <p>加载失败：${error.message}</p>
            </div>
        `;
    }
}

// 刷新回收站列表
window.refreshRecycleBin = async function() {
    await loadRecycleBin();
    showToast('回收站已刷新');
};

// 恢复项目
window.restoreProject = async function(projectId, projectName) {
    const confirmed = await showConfirm(
        `确定要恢复项目 "${projectName}" 吗？`,
        {
            title: '恢复项目',
            type: 'info',
            okText: '恢复',
            cancelText: '取消'
        }
    );
    
    if (!confirmed) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/projects/recycle-bin/${projectId}/restore`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || '恢复项目失败');
        }
        
        showAlert('项目已恢复', 'success');
        
        // 刷新回收站列表
        await loadRecycleBin();
        
        // 刷新项目列表
        await loadProjects();
    } catch (error) {
        showAlert('恢复项目失败: ' + error.message, 'error');
    }
};

// 彻底删除项目
window.permanentlyDeleteProject = async function(projectId, projectName) {
    const confirmed = await showConfirm(
        `确定要彻底删除项目 "${projectName}" 吗？\n\n⚠️ 此操作将永久删除项目文件夹和所有数据，无法恢复！`,
        {
            title: '彻底删除项目',
            type: 'danger',
            okText: '彻底删除',
            cancelText: '取消'
        }
    );
    
    if (!confirmed) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/projects/recycle-bin/${projectId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || '删除项目失败');
        }
        
        showAlert('项目已彻底删除', 'success');
        
        // 刷新回收站列表
        await loadRecycleBin();
    } catch (error) {
        showAlert('删除项目失败: ' + error.message, 'error');
    }
};

// 清空回收站
window.clearRecycleBin = async function() {
    const confirmed = await showConfirm(
        `确定要清空回收站吗？\n\n⚠️ 此操作将彻底删除回收站中的所有项目，无法恢复！`,
        {
            title: '清空回收站',
            type: 'danger',
            okText: '清空',
            cancelText: '取消'
        }
    );
    
    if (!confirmed) {
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/projects/recycle-bin/clear`, {
            method: 'POST'
        });
        
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || '清空回收站失败');
        }
        
        showAlert(result.message || '回收站已清空', 'success');
        
        // 刷新回收站列表
        await loadRecycleBin();
    } catch (error) {
        showAlert('清空回收站失败: ' + error.message, 'error');
    }
};

// 设置默认项目
window.setDefaultProject = async function(projectId, projectName) {
    try {
        await projectAPI.setDefaultProject(projectId);
        showAlert('默认项目已设置', 'success');
        
        // 只刷新项目列表，不刷新场景列表
        await loadProjects();
    } catch (error) {
        showAlert('设置默认项目失败: ' + error.message, 'error');
    }
};

// 打开项目设置弹窗
window.openProjectSettingsModal = async function(projectId) {
    try {
        const project = await projectAPI.getProject(projectId);
        const modal = document.getElementById('projectSettingsModal');
        if (!modal) return;
        
        // 填充当前设置
        document.getElementById('settingsProjectId').value = projectId;
        document.getElementById('settingsProjectName').textContent = project.name;
        document.getElementById('settingsMaxConcurrent').value = project.maxConcurrentDownloads || 3;
        document.getElementById('settingsConcurrentValue').textContent = project.maxConcurrentDownloads || 3;
        
        modal.style.display = 'flex';
    } catch (error) {
        showAlert('加载项目设置失败: ' + error.message, 'error');
    }
};

// 关闭项目设置弹窗
window.closeProjectSettingsModal = function() {
    const modal = document.getElementById('projectSettingsModal');
    if (modal) {
        modal.style.display = 'none';
    }
};

// 保存项目设置
window.saveProjectSettings = async function() {
    const projectId = document.getElementById('settingsProjectId').value;
    const maxConcurrentDownloads = parseInt(document.getElementById('settingsMaxConcurrent').value, 10);
    
    // 验证输入
    if (isNaN(maxConcurrentDownloads) || maxConcurrentDownloads < 1 || maxConcurrentDownloads > 20) {
        showAlert('批量下载并发数必须在 1-20 之间', 'error');
        return;
    }
    
    try {
        await projectAPI.updateProject(projectId, { 
            maxConcurrentDownloads: maxConcurrentDownloads
        });
        showAlert('项目设置已保存', 'success');
        closeProjectSettingsModal();
        await loadProjects();
    } catch (error) {
        showAlert('保存设置失败: ' + error.message, 'error');
    }
};

// ============================================
// 场景管理功能
// ============================================

// 选择项目并加载其场景
window.selectProject = async function(projectId) {
    selectedProjectId = projectId;
    
    // 启用创建场景按钮
    const createSceneBtn = document.getElementById('createSceneBtn');
    if (createSceneBtn) {
        createSceneBtn.disabled = false;
    }
    
    // 刷新项目列表以显示选中状态
    await loadProjects();
    
    // 加载该项目的场景
    await loadProjectScenes();
    
    // 滚动到场景列表区域
    const scenesContainer = document.getElementById('scenesContainer');
    scenesContainer.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
};

// 加载项目的场景列表
window.loadProjectScenes = async function() {
    const container = document.getElementById('scenesContainer');
    const projectNameDisplay = document.getElementById('selectedProjectName');
    
    if (!selectedProjectId) {
        container.innerHTML = '<div style="text-align: center; padding: 40px; color: #999;">请在上方项目列表中点击项目名称</div>';
        if (projectNameDisplay) {
            projectNameDisplay.textContent = '未选择项目';
            projectNameDisplay.style.color = '#999';
        }
        return;
    }
    
    container.innerHTML = '<div class="loading" style="text-align: center; padding: 40px;">加载中...</div>';
    
    try {
        const projectData = await projectAPI.getProject(selectedProjectId);
        selectedProjectForScenes = projectData;
        const scenes = projectData.scenes || [];
        
        
        // 更新选中项目名称显示
        if (projectNameDisplay) {
            projectNameDisplay.textContent = `当前项目：${projectData.name}`;
            projectNameDisplay.style.color = '#667eea';
        }
        
        if (scenes.length === 0) {
            container.innerHTML = '<div style="text-align: center; padding: 40px; color: #999;">该项目暂无场景</div>';
            // 保持创建场景按钮的启用状态
            const createSceneBtn = document.getElementById('createSceneBtn');
            if (createSceneBtn && selectedProjectId) {
                createSceneBtn.disabled = false;
            }
            return;
        }
        
        let html = `
            <table class="data-table">
                <thead>
                    <tr>
                        <th>场景名称</th>
                        <th>类型</th>
                        <th>描述</th>
                        <th>状态</th>
                        <th>更新时间</th>
                        <th style="width: 180px;">操作</th>
                    </tr>
                </thead>
                <tbody>
        `;
        
        scenes.forEach((scene, index) => {
            // 只使用defaultScene字段判断默认场景，确保只有一个默认
            const isDefault = scene.id === projectData.defaultScene;
            const updatedAt = new Date(scene.updatedAt || scene.createdAt).toLocaleString('zh-CN');
            
            html += `
                <tr>
                    <td><strong>${scene.icon || '🏞️'} ${scene.name}</strong></td>
                    <td>${scene.type}</td>
                    <td>${scene.description || '-'}</td>
                    <td>
                        ${isDefault ? '<span class="badge badge-default">默认</span>' : ''}
                    </td>
                    <td>${updatedAt}</td>
                    <td>
                        ${!isDefault ? `<button type="button" class="btn-sm btn-switch" onclick="setDefaultScene('${selectedProjectId}', '${scene.id}', '${scene.name.replace(/'/g, "\\'")}')">设为默认</button>` : ''}
                        ${!isDefault ? `<button type="button" class="btn-sm btn-delete" onclick="deleteScene('${selectedProjectId}', '${scene.id}', '${scene.name.replace(/'/g, "\\'")}')">删除</button>` : '<span style="color: #999; font-size: 12px;">默认场景</span>'}
                    </td>
                </tr>
            `;
        });
        
        html += '</tbody></table>';
        container.innerHTML = html;
        
        // 保持创建场景按钮的启用状态
        const createSceneBtn = document.getElementById('createSceneBtn');
        if (createSceneBtn && selectedProjectId) {
            createSceneBtn.disabled = false;
        }
        
    } catch (error) {
        console.error('加载场景失败:', error);
        container.innerHTML = `<div style="text-align: center; padding: 40px; color: #e53e3e;">加载失败: ${error.message}</div>`;
        // 即使加载失败，如果有选中项目，也保持按钮启用
        const createSceneBtn = document.getElementById('createSceneBtn');
        if (createSceneBtn && selectedProjectId) {
            createSceneBtn.disabled = false;
        }
    }
};

// 移动场景顺序
window.moveScene = async function(projectId, currentIndex, direction) {
    if (!selectedProjectForScenes) return;
    const scenes = selectedProjectForScenes.scenes;
    
    const newIndex = currentIndex + direction;
    if (newIndex < 0 || newIndex >= scenes.length) return;
    
    try {
        // 交换位置
        const temp = scenes[currentIndex];
        scenes[currentIndex] = scenes[newIndex];
        scenes[newIndex] = temp;
        
        // 调用API保存新的顺序
        await projectAPI.updateSceneOrder(selectedProjectId, scenes.map(s => s.id));
        
        // 刷新场景列表
        await loadProjectScenes();
    } catch (error) {
        console.error('❌ 移动场景失败:', error);
        showAlert('调整顺序失败: ' + error.message, 'error');
        // 失败时重新加载恢复原顺序
        await loadProjectScenes();
    }
};

// 设置默认场景
window.setDefaultScene = async function(projectId, sceneId, sceneName) {
    const confirmed = await showConfirm(
        `确定将 "${sceneName}" 设为默认场景吗？\n\n进入项目后将自动加载此场景。`,
        {
            title: '设置默认场景',
            type: 'info',
            okText: '设置',
            cancelText: '取消'
        }
    );
    
    if (!confirmed) {
        return;
    }
    
    try {
        await projectAPI.setDefaultScene(projectId, sceneId);
        showAlert('默认场景已设置', 'success');
        await loadProjectScenes();
    } catch (error) {
        showAlert('设置默认场景失败: ' + error.message, 'error');
    }
};

// 删除场景
window.deleteScene = async function(projectId, sceneId, sceneName) {
    const confirmed = await showConfirm(
        `确定要删除场景 "${sceneName}" 吗？\n\n⚠️ 此操作不可恢复！`,
        {
            title: '删除场景',
            type: 'danger',
            okText: '删除',
            cancelText: '取消'
        }
    );
    
    if (!confirmed) {
        return;
    }
    
    try {
        await projectAPI.deleteScene(projectId, sceneId);
        showAlert(`场景 "${sceneName}" 已删除`, 'success');
        await loadProjectScenes();
        await updateProjectSceneCount(projectId);
    } catch (error) {
        console.error('❌ 删除场景失败:', error);
        showAlert(error.message || '删除场景失败', 'error');
    }
};

// ============================================
// 创建项目功能
// ============================================

// 打开创建项目Modal
window.openCreateProjectModal = function() {
    const modal = document.getElementById('createProjectModal');
    modal.style.display = 'flex';
    document.getElementById('newProjectName').value = '';
    document.getElementById('newProjectDescription').value = '';
    document.getElementById('newProjectName').focus();
};

// 关闭创建项目Modal
window.closeCreateProjectModal = function() {
    document.getElementById('createProjectModal').style.display = 'none';
};

// 确认创建项目
window.confirmCreateProject = async function() {
    // 防止重复点击
    if (window.isCreatingProject) {
        console.warn('⚠️ 项目正在创建中，请勿重复点击');
        return;
    }

    const name = document.getElementById('newProjectName').value.trim();
    const description = document.getElementById('newProjectDescription').value.trim();

    if (!name) {
        showAlert('请输入项目名称', 'error');
        return;
    }

    // 设置创建中标志并禁用按钮
    window.isCreatingProject = true;
    const modal = document.getElementById('createProjectModal');
    const createBtn = modal.querySelector('button[onclick="confirmCreateProject()"]');
    const originalBtnText = createBtn.textContent;
    createBtn.disabled = true;
    createBtn.textContent = '创建中...';
    createBtn.style.opacity = '0.6';
    createBtn.style.cursor = 'not-allowed';

    try {
        await projectAPI.createProject(name, description);
        showAlert(`项目 "${name}" 创建成功！`, 'success');
        closeCreateProjectModal();
        await loadProjects();
    } catch (error) {
        showAlert('创建项目失败: ' + error.message, 'error');
    } finally {
        // 恢复按钮状态
        window.isCreatingProject = false;
        createBtn.disabled = false;
        createBtn.textContent = originalBtnText;
        createBtn.style.opacity = '1';
        createBtn.style.cursor = 'pointer';
    }
};

// ============================================
// 创建场景功能
// ============================================

// 打开创建场景Modal
window.openCreateSceneModal = function() {
    if (!selectedProjectId) {
        showAlert('请先选择一个项目', 'error');
        return;
    }
    const modal = document.getElementById('createSceneModalAdmin');
    modal.style.display = 'flex';
    document.getElementById('newSceneNameAdmin').value = '';
    document.getElementById('newSceneDescriptionAdmin').value = '';
    document.getElementById('newSceneNameAdmin').focus();
};

// 关闭创建场景Modal
window.closeCreateSceneModalAdmin = function() {
    document.getElementById('createSceneModalAdmin').style.display = 'none';
};

// 确认创建场景
window.confirmCreateSceneAdmin = async function() {
    if (!selectedProjectId) {
        showAlert('请先选择一个项目', 'error');
        return;
    }

    const name = document.getElementById('newSceneNameAdmin').value.trim();
    const description = document.getElementById('newSceneDescriptionAdmin').value.trim();

    if (!name) {
        showAlert('请输入场景名称', 'error');
        return;
    }

    try {
        await projectAPI.addScene(selectedProjectId, {
            name,
            description,
            type: 'GroundScene'
        });
        
        showAlert(`场景 "${name}" 创建成功！`, 'success');
        closeCreateSceneModalAdmin();
        await loadProjectScenes();
        await updateProjectSceneCount(selectedProjectId); // 只更新场景数，不重新加载整个列表
    } catch (error) {
        showAlert('创建场景失败: ' + error.message, 'error');
    }
};

// ============================================
// 资源管理功能
// ============================================

// 全局变量存储当前资源数据
let currentResourceData = null;
let currentSelectedProject = null;

// 加载资源分析数据
window.loadResourceAnalysis = async function() {
    const projectSelector = document.getElementById('resourceProjectSelector');
    const projectId = projectSelector.value;
    
    if (!projectId) {
        // 隐藏统计和Tab，显示空状态
        document.getElementById('resourcesOverview').style.display = 'none';
        document.getElementById('resourceTabContainer').style.display = 'none';
        document.getElementById('resourcesEmptyState').style.display = 'block';
        return;
    }
    
    try {
        // 显示加载状态
        document.getElementById('resourcesEmptyState').innerHTML = '<div class="loading-state"><div class="loading"></div><p>正在分析资源...</p></div>';
        document.getElementById('resourcesEmptyState').style.display = 'block';
        document.getElementById('resourcesOverview').style.display = 'none';
        document.getElementById('resourceTabContainer').style.display = 'none';
        
        const response = await fetch(`${API_BASE_URL}/resources/${projectId}/analysis`);
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || '加载资源分析失败');
        }
        
        currentResourceData = result.data;
        currentSelectedProject = projectId;
        
        // 更新统计卡片
        updateResourceStatistics(result.data.statistics);
        
        // 显示统计和Tab
        document.getElementById('resourcesEmptyState').style.display = 'none';
        document.getElementById('resourcesOverview').style.display = 'block';
        document.getElementById('resourceTabContainer').style.display = 'block';
        
        // 渲染资源列表
        renderScenesAnalysis(result.data.sceneAnalysis || []);
        renderModelsTable(result.data.models);
        renderMaterialsTable(result.data.materials);
        renderTexturesTable(result.data.textures);
        
        showToast('资源分析完成', 'success');
        
    } catch (error) {
        console.error('❌ 加载资源分析失败:', error);
        document.getElementById('resourcesEmptyState').innerHTML = `
            <div class="error-state">
                <div style="font-size: 48px; margin-bottom: 20px;">❌</div>
                <p>加载失败: ${error.message}</p>
            </div>
        `;
        document.getElementById('resourcesEmptyState').style.display = 'block';
        document.getElementById('resourcesOverview').style.display = 'none';
        document.getElementById('resourceTabContainer').style.display = 'none';
    }
};

// 更新资源统计卡片
function updateResourceStatistics(stats) {
    // 模型统计
    document.getElementById('statsModelsTotal').textContent = stats.models.total;
    document.getElementById('statsModelsUsed').textContent = stats.models.used;
    document.getElementById('statsModelsUnused').textContent = stats.models.unused;
    document.getElementById('statsModelsRate').textContent = stats.models.usageRate;
    document.getElementById('statsModelsBar').style.width = stats.models.usageRate;
    
    // 材质统计
    document.getElementById('statsMaterialsTotal').textContent = stats.materials.total;
    document.getElementById('statsMaterialsUsed').textContent = stats.materials.used;
    document.getElementById('statsMaterialsUnused').textContent = stats.materials.unused;
    document.getElementById('statsMaterialsRate').textContent = stats.materials.usageRate;
    document.getElementById('statsMaterialsBar').style.width = stats.materials.usageRate;
    
    // 贴图统计
    document.getElementById('statsTexturesTotal').textContent = stats.textures.total;
    document.getElementById('statsTexturesUsed').textContent = stats.textures.used;
    document.getElementById('statsTexturesUnused').textContent = stats.textures.unused;
    document.getElementById('statsTexturesRate').textContent = stats.textures.usageRate;
    document.getElementById('statsTexturesBar').style.width = stats.textures.usageRate;
}

// 切换资源Tab
window.switchResourceTab = function(tabName) {
    // 更新Tab按钮状态
    document.querySelectorAll('.resource-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelector(`.resource-tab[data-tab="${tabName}"]`).classList.add('active');
    
    // 更新Tab内容显示
    document.querySelectorAll('.resource-tab-content').forEach(content => {
        content.classList.remove('active');
    });
    document.getElementById(`${tabName}Tab`).classList.add('active');
};

// 渲染场景分析
function renderScenesAnalysis(sceneAnalysis) {
    const tabsContainer = document.getElementById('sceneTabsContainer');
    const contentContainer = document.getElementById('sceneContentContainer');
    
    if (sceneAnalysis.length === 0) {
        tabsContainer.style.display = 'none';
        contentContainer.innerHTML = '<div class="empty-state"><p>暂无场景数据</p></div>';
        return;
    }
    
    // 显示Tab容器
    tabsContainer.style.display = 'block';
    
    // 生成场景Tab按钮
    let tabsHtml = '';
    sceneAnalysis.forEach((scene, index) => {
        const isActive = index === 0 ? 'active' : '';
        tabsHtml += `
            <button type="button" class="scene-sub-tab ${isActive}" data-scene-id="${scene.sceneId}" onclick="switchSceneTab('${scene.sceneId}')">
                🎬 ${escapeHtml(scene.sceneName)}
            </button>
        `;
    });
    tabsContainer.innerHTML = tabsHtml;
    
    // 生成场景内容
    let contentHtml = '';
    sceneAnalysis.forEach((scene, index) => {
        const isActive = index === 0 ? 'active' : '';
        contentHtml += renderSceneContent(scene, isActive);
    });
    contentContainer.innerHTML = contentHtml;
}

// 渲染单个场景的内容
function renderSceneContent(scene, activeClass = '') {
    const stats = scene.statistics;
    const perf = scene.performance;
    const resources = scene.resources;
    
    // 性能等级配置
    const perfConfig = {
        'excellent': { color: '#10b981', bgColor: '#d1fae5', text: '优秀', icon: '🌟' },
        'good': { color: '#3b82f6', bgColor: '#dbeafe', text: '良好', icon: '✅' },
        'fair': { color: '#f59e0b', bgColor: '#fef3c7', text: '一般', icon: '⚠️' },
        'poor': { color: '#ef4444', bgColor: '#fee2e2', text: '较差', icon: '❌' }
    };
    const perfInfo = perfConfig[perf.level] || perfConfig.fair;
    
    // 性能指标状态判断函数
    const getMetricStatus = (value, goodThreshold, warningThreshold) => {
        if (value <= goodThreshold) return { class: 'good', text: '✓ 正常' };
        if (value <= warningThreshold) return { class: 'warning', text: '⚠ 注意' };
        return { class: 'danger', text: '✗ 超标' };
    };
    
    const totalSizeMB = stats.totalSize / 1024 / 1024;
    const sizeStatus = getMetricStatus(totalSizeMB, 10, 20);
    const resourceStatus = getMetricStatus(stats.totalResourceCount, 50, 80);
    const modelStatus = getMetricStatus(stats.modelCount, 20, 30);
    const textureStatus = getMetricStatus(stats.textureCount, 15, 25);
    
    return `
        <div class="scene-content ${activeClass}" data-scene-id="${scene.sceneId}">
            <!-- 性能总览 -->
            <div style="background: white; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h3 style="margin: 0; font-size: 18px; color: #333;">📊 性能总评</h3>
                    <div style="display: inline-block; padding: 8px 16px; background: ${perfInfo.bgColor}; color: ${perfInfo.color}; border-radius: 8px; font-weight: 600; font-size: 14px;">
                        ${perfInfo.icon} ${perfInfo.text} ${perf.score}分
                    </div>
                </div>
                
                <div style="background: #f9fafb; border-radius: 8px; padding: 15px; margin-bottom: 15px;">
                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                        <span style="font-size: 20px;">⏱️</span>
                        <div>
                            <div style="font-weight: 600; color: #333;">预估加载时间</div>
                            <div style="color: #666; font-size: 13px;">基于资源大小和数量的综合评估</div>
                        </div>
                    </div>
                    <div style="font-size: 32px; font-weight: bold; color: #667eea; text-align: center; padding: 10px 0;">
                        ${perf.estimatedLoadTime} ms
                    </div>
                </div>
                
                ${perf.suggestions.length > 0 ? `
                    <div style="background: #f9fafb; border-left: 4px solid ${perfInfo.color}; padding: 15px; border-radius: 6px;">
                        <div style="font-weight: 600; color: #333; margin-bottom: 10px; display: flex; align-items: center; gap: 8px;">
                            <span>💡</span>
                            <span>优化建议</span>
                        </div>
                        <ul style="margin: 0; padding-left: 20px; color: #666; font-size: 13px; line-height: 1.8;">
                            ${perf.suggestions.map(s => `<li>${escapeHtml(s)}</li>`).join('')}
                        </ul>
                    </div>
                ` : ''}
            </div>
            
            <!-- 详细性能指标 -->
            <div style="background: white; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <h3 style="margin: 0 0 20px 0; font-size: 18px; color: #333;">🔍 性能指标分析</h3>
                <div class="performance-metrics">
                    <div class="metric-card">
                        <div class="metric-label">总文件大小</div>
                        <div class="metric-value">${formatFileSize(stats.totalSize)}</div>
                        <div class="metric-status ${sizeStatus.class}">${sizeStatus.text}</div>
                        <div style="font-size: 11px; color: #9ca3af; margin-top: 5px;">
                            标准: ≤10MB 良好, ≤20MB 可接受
                        </div>
                    </div>
                    
                    <div class="metric-card">
                        <div class="metric-label">总资源数量</div>
                        <div class="metric-value">${stats.totalResourceCount}</div>
                        <div class="metric-status ${resourceStatus.class}">${resourceStatus.text}</div>
                        <div style="font-size: 11px; color: #9ca3af; margin-top: 5px;">
                            标准: ≤50 良好, ≤80 可接受
                        </div>
                    </div>
                    
                    <div class="metric-card">
                        <div class="metric-label">模型数量</div>
                        <div class="metric-value">${stats.modelCount}</div>
                        <div class="metric-status ${modelStatus.class}">${modelStatus.text}</div>
                        <div style="font-size: 11px; color: #9ca3af; margin-top: 5px;">
                            标准: ≤20 良好, ≤30 可接受
                        </div>
                    </div>
                    
                    <div class="metric-card">
                        <div class="metric-label">模型总大小</div>
                        <div class="metric-value">${formatFileSize(stats.totalModelSize)}</div>
                        <div class="metric-status">${(stats.totalModelSize / stats.totalSize * 100).toFixed(1)}% 占比</div>
                    </div>
                    
                    <div class="metric-card">
                        <div class="metric-label">材质数量</div>
                        <div class="metric-value">${stats.materialCount}</div>
                        <div class="metric-status">${stats.materialCount} 个材质</div>
                        <div style="font-size: 11px; color: #9ca3af; margin-top: 5px;">
                            材质影响渲染性能
                        </div>
                    </div>
                    
                    <div class="metric-card">
                        <div class="metric-label">贴图数量</div>
                        <div class="metric-value">${stats.textureCount}</div>
                        <div class="metric-status ${textureStatus.class}">${textureStatus.text}</div>
                        <div style="font-size: 11px; color: #9ca3af; margin-top: 5px;">
                            标准: ≤15 良好, ≤25 可接受
                        </div>
                    </div>
                    
                    <div class="metric-card">
                        <div class="metric-label">贴图总大小</div>
                        <div class="metric-value">${formatFileSize(stats.totalTextureSize)}</div>
                        <div class="metric-status">${(stats.totalTextureSize / stats.totalSize * 100).toFixed(1)}% 占比</div>
                    </div>
                    
                    <div class="metric-card" style="background: linear-gradient(135deg, #667eea15 0%, #764ba215 100%);">
                        <div class="metric-label">性能评分</div>
                        <div class="metric-value" style="color: ${perfInfo.color};">${perf.score}</div>
                        <div class="metric-status" style="color: ${perfInfo.color}; font-weight: 600;">${perfInfo.text}</div>
                    </div>
                </div>
            </div>
            
            <!-- 模型列表 -->
            <div style="background: white; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <h3 style="margin: 0 0 15px 0; font-size: 18px; color: #333;">
                    🎨 模型列表 (${resources.models.length})
                </h3>
                ${resources.models.length > 0 ? `
                    <table class="resource-table">
                        <thead>
                            <tr>
                                <th>模型名称</th>
                                <th>文件名</th>
                                <th>格式</th>
                                <th>大小</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${resources.models.map(model => `
                                <tr>
                                    <td><strong>${escapeHtml(model.name)}</strong></td>
                                    <td>${escapeHtml(model.filename)}</td>
                                    <td>${model.format.toUpperCase()}</td>
                                    <td>${formatFileSize(model.size)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                ` : '<div class="empty-state"><p>该场景未使用任何模型</p></div>'}
            </div>
            
            <!-- 材质列表 -->
            <div style="background: white; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <h3 style="margin: 0 0 15px 0; font-size: 18px; color: #333;">
                    🎭 材质列表 (${resources.materials.length})
                </h3>
                ${resources.materials.length > 0 ? `
                    <table class="resource-table">
                        <thead>
                            <tr>
                                <th>材质名称</th>
                                <th>颜色</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${resources.materials.map(material => `
                                <tr>
                                    <td><strong>${escapeHtml(material.name)}</strong></td>
                                    <td>
                                        <div style="display: flex; align-items: center; gap: 8px;">
                                            <div style="width: 24px; height: 24px; border-radius: 4px; background: ${material.color}; border: 1px solid #ddd;"></div>
                                            <span>${material.color}</span>
                                        </div>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                ` : '<div class="empty-state"><p>该场景未使用任何材质</p></div>'}
            </div>
            
            <!-- 贴图列表 -->
            <div style="background: white; border-radius: 12px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                <h3 style="margin: 0 0 15px 0; font-size: 18px; color: #333;">
                    🖼️ 贴图列表 (${resources.textures.length})
                </h3>
                ${resources.textures.length > 0 ? `
                    <table class="resource-table">
                        <thead>
                            <tr>
                                <th>贴图名称</th>
                                <th>文件名</th>
                                <th>类型</th>
                                <th>大小</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${resources.textures.map(texture => `
                                <tr>
                                    <td><strong>${escapeHtml(texture.name)}</strong></td>
                                    <td>${escapeHtml(texture.filename)}</td>
                                    <td>${texture.mimetype || '-'}</td>
                                    <td>${formatFileSize(texture.size)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>
                ` : '<div class="empty-state"><p>该场景未使用任何贴图</p></div>'}
            </div>
        </div>
    `;
}

// 切换场景Tab
window.switchSceneTab = function(sceneId) {
    // 更新Tab按钮状态
    document.querySelectorAll('.scene-sub-tab').forEach(tab => {
        tab.classList.remove('active');
    });
    document.querySelector(`.scene-sub-tab[data-scene-id="${sceneId}"]`).classList.add('active');
    
    // 更新内容显示
    document.querySelectorAll('.scene-content').forEach(content => {
        content.classList.remove('active');
    });
    document.querySelector(`.scene-content[data-scene-id="${sceneId}"]`).classList.add('active');
};

// 渲染模型列表
function renderModelsTable(models) {
    const container = document.getElementById('modelsTableContainer');
    
    if (models.length === 0) {
        container.innerHTML = '<div class="empty-state"><p>暂无模型资源</p></div>';
        return;
    }
    
    let html = `
        <table class="resource-table">
            <thead>
                <tr>
                    <th>模型名称</th>
                    <th>文件名</th>
                    <th>格式</th>
                    <th>大小</th>
                    <th>使用材质数</th>
                    <th>使用场景</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    models.forEach(model => {
        const size = formatFileSize(model.size);
        const status = model.usedInScenes ? '已使用' : '未使用';
        const statusClass = model.usedInScenes ? 'used' : 'unused';
        const sceneCount = model.sceneUsage.length;
        
        html += `
            <tr data-used="${model.usedInScenes}">
                <td><strong>${escapeHtml(model.name)}</strong></td>
                <td>${escapeHtml(model.filename)}</td>
                <td>${model.format.toUpperCase()}</td>
                <td>${size}</td>
                <td>${model.materialCount}</td>
                <td>${sceneCount > 0 ? `${sceneCount} 个场景` : '-'}</td>
                <td><span class="status-badge ${statusClass}">${status}</span></td>
                <td>
                    <button type="button" class="btn-dependency" onclick="showResourceDependencies('model', '${model.id}')">
                        查看依赖
                    </button>
                </td>
            </tr>
        `;
    });
    
    html += '</tbody></table>';
    container.innerHTML = html;
}

// 渲染材质列表
function renderMaterialsTable(materials) {
    const container = document.getElementById('materialsTableContainer');
    
    if (materials.length === 0) {
        container.innerHTML = '<div class="empty-state"><p>暂无材质资源</p></div>';
        return;
    }
    
    let html = `
        <table class="resource-table">
            <thead>
                <tr>
                    <th>材质名称</th>
                    <th>颜色</th>
                    <th>金属度</th>
                    <th>粗糙度</th>
                    <th>使用贴图数</th>
                    <th>使用模型</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    materials.forEach(material => {
        const status = material.usedByModels ? '已使用' : '未使用';
        const statusClass = material.usedByModels ? 'used' : 'unused';
        const modelCount = material.modelUsage.length;
        
        html += `
            <tr data-used="${material.usedByModels}">
                <td><strong>${escapeHtml(material.name)}</strong></td>
                <td>
                    <div style="display: flex; align-items: center; gap: 8px;">
                        <div style="width: 20px; height: 20px; border-radius: 4px; background: ${material.color}; border: 1px solid #ddd;"></div>
                        <span>${material.color}</span>
                    </div>
                </td>
                <td>${material.metalness}</td>
                <td>${material.roughness}</td>
                <td>${material.textureCount}</td>
                <td>${modelCount > 0 ? `${modelCount} 个模型` : '-'}</td>
                <td><span class="status-badge ${statusClass}">${status}</span></td>
                <td>
                    <button type="button" class="btn-dependency" onclick="showResourceDependencies('material', '${material.id}')">
                        查看依赖
                    </button>
                </td>
            </tr>
        `;
    });
    
    html += '</tbody></table>';
    container.innerHTML = html;
}

// 渲染贴图列表
function renderTexturesTable(textures) {
    const container = document.getElementById('texturesTableContainer');
    
    if (textures.length === 0) {
        container.innerHTML = '<div class="empty-state"><p>暂无贴图资源</p></div>';
        return;
    }
    
    let html = `
        <table class="resource-table">
            <thead>
                <tr>
                    <th>贴图名称</th>
                    <th>文件名</th>
                    <th>类型</th>
                    <th>大小</th>
                    <th>尺寸</th>
                    <th>使用材质</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    textures.forEach(texture => {
        const size = formatFileSize(texture.size);
        const dimensions = texture.width && texture.height ? `${texture.width} × ${texture.height}` : '-';
        const status = texture.usedByMaterials ? '已使用' : '未使用';
        const statusClass = texture.usedByMaterials ? 'used' : 'unused';
        const materialCount = texture.materialUsage.length;
        
        html += `
            <tr data-used="${texture.usedByMaterials}">
                <td><strong>${escapeHtml(texture.name)}</strong></td>
                <td>${escapeHtml(texture.filename)}</td>
                <td>${texture.mimetype || '-'}</td>
                <td>${size}</td>
                <td>${dimensions}</td>
                <td>${materialCount > 0 ? `${materialCount} 个材质` : '-'}</td>
                <td><span class="status-badge ${statusClass}">${status}</span></td>
                <td>
                    <button type="button" class="btn-dependency" onclick="showResourceDependencies('texture', '${texture.id}')">
                        查看依赖
                    </button>
                </td>
            </tr>
        `;
    });
    
    html += '</tbody></table>';
    container.innerHTML = html;
}

// 显示资源依赖详情
window.showResourceDependencies = async function(resourceType, resourceId) {
    if (!currentSelectedProject) {
        showToast('请先选择项目', 'error');
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/resources/${currentSelectedProject}/${resourceType}/${resourceId}/dependencies`);
        const result = await response.json();
        
        if (!result.success) {
            throw new Error(result.error || '获取依赖信息失败');
        }
        
        showDependencyModal(result.data);
        
    } catch (error) {
        console.error('❌ 获取依赖信息失败:', error);
        showToast('获取依赖信息失败: ' + error.message, 'error');
    }
};

// 显示依赖详情弹窗
function showDependencyModal(dependencies) {
    // 创建弹窗
    const modal = document.createElement('div');
    modal.className = 'resource-detail-modal';
    modal.onclick = (e) => {
        if (e.target === modal) {
            modal.remove();
        }
    };
    
    const resourceTypeNames = {
        'model': '模型',
        'material': '材质',
        'texture': '贴图',
        'scene': '场景'
    };
    
    let dependsOnHtml = '';
    if (dependencies.dependsOn.length > 0) {
        dependsOnHtml = '<ul class="dependency-list">';
        dependencies.dependsOn.forEach(dep => {
            const icon = dep.type === 'material' ? '🎭' : dep.type === 'texture' ? '🖼️' : '📦';
            const extra = dep.textureType ? ` (${dep.textureType})` : '';
            dependsOnHtml += `
                <li>
                    <span>${icon}</span>
                    <strong>${resourceTypeNames[dep.type]}:</strong>
                    <span>${escapeHtml(dep.name)}${extra}</span>
                </li>
            `;
        });
        dependsOnHtml += '</ul>';
    } else {
        dependsOnHtml = '<p style="color: #999;">无依赖项</p>';
    }
    
    let usedByHtml = '';
    if (dependencies.usedBy.length > 0) {
        usedByHtml = '<ul class="dependency-list">';
        dependencies.usedBy.forEach(user => {
            const icon = user.type === 'model' ? '🎨' : user.type === 'material' ? '🎭' : user.type === 'scene' ? '🎬' : '📦';
            const extra = user.meshName ? ` (${user.meshName})` : user.objectName ? ` (${user.objectName})` : user.textureType ? ` (${user.textureType})` : '';
            usedByHtml += `
                <li>
                    <span>${icon}</span>
                    <strong>${resourceTypeNames[user.type]}:</strong>
                    <span>${escapeHtml(user.name)}${extra}</span>
                </li>
            `;
        });
        usedByHtml += '</ul>';
    } else {
        usedByHtml = '<p style="color: #999;">未被使用</p>';
    }
    
    modal.innerHTML = `
        <div class="resource-detail-content">
            <div class="resource-detail-header">
                <h3>📋 资源依赖关系</h3>
                <button type="button" onclick="this.closest('.resource-detail-modal').remove()" style="background: none; border: none; font-size: 24px; color: #999; cursor: pointer; padding: 0; line-height: 1;">&times;</button>
            </div>
            <div class="resource-detail-body">
                <div class="dependency-section">
                    <h4>🔽 该资源依赖的资源</h4>
                    ${dependsOnHtml}
                </div>
                <div class="dependency-section">
                    <h4>🔼 使用该资源的资源</h4>
                    ${usedByHtml}
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
}

// 过滤资源表格
window.filterResourceTable = function(resourceType) {
    const checkboxId = `filterUnused${capitalizeFirst(resourceType)}`;
    const checkbox = document.getElementById(checkboxId);
    const showOnlyUnused = checkbox.checked;
    
    const tabContainer = document.getElementById(`${resourceType}Tab`);
    const rows = tabContainer.querySelectorAll('table tbody tr');
    
    rows.forEach(row => {
        const isUsed = row.getAttribute('data-used') === 'true';
        if (showOnlyUnused && isUsed) {
            row.style.display = 'none';
        } else {
            row.style.display = '';
        }
    });
};

// 加载项目列表到资源管理的选择器
async function loadResourceProjectSelector() {
    try {
        const data = await projectAPI.getAllProjects();
        const projects = data.projects || [];
        
        const selector = document.getElementById('resourceProjectSelector');
        if (!selector) return; // 如果元素不存在则退出
        
        selector.innerHTML = '<option value="">-- 请选择项目 --</option>';
        
        projects.forEach(project => {
            const option = document.createElement('option');
            option.value = project.id;
            option.textContent = project.name;
            selector.appendChild(option);
        });
        
    } catch (error) {
        console.error('❌ 加载项目列表失败:', error);
    }
}

// 工具函数
function formatFileSize(bytes) {
    if (!bytes || bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
}

function capitalizeFirst(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// ============================================
// 账号管理功能
// ============================================


// 更新项目密码
window.updateProjectPassword = async function() {
    const password = document.getElementById('auth-projectPassword').value.trim();
    
    if (!password) {
        showAlert('请输入新密码', 'error');
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/accounts/users/user-default`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ password })
        });
        
        const result = await response.json();
        
        if (result.success) {
            showAlert('项目登录密码更新成功', 'success');
            document.getElementById('auth-projectPassword').value = '';
        } else {
            showAlert(result.error || '密码更新失败', 'error');
        }
        
    } catch (error) {
        console.error('❌ 更新项目密码失败:', error);
        showAlert('网络错误，请稍后重试', 'error');
    }
};

// 更新管理员密码
window.updateAdminPassword = async function() {
    const password = document.getElementById('auth-adminPassword').value.trim();
    
    if (!password) {
        showAlert('请输入新密码', 'error');
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE_URL}/accounts/admins/admin-default`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ password })
        });
        
        const result = await response.json();
        
        if (result.success) {
            showAlert('管理员密码更新成功', 'success');
            document.getElementById('auth-adminPassword').value = '';
        } else {
            showAlert(result.error || '密码更新失败', 'error');
        }
        
    } catch (error) {
        console.error('❌ 更新管理员密码失败:', error);
        showAlert('网络错误，请稍后重试', 'error');
    }
};


